<template>
  <div class="product-items" :class="{show:show}">
    <div class="pi-bg" @click="close"></div>
    <div class="pi-main">
      <div :class="isShowImg?'flex pi-top':'textRight pi-top'">
        <!-- <div class="flex pi-top" > -->
        <div class="pi-img" v-if="isShowImg">
          <img :src="info.colorimg||info.mainpic|https" alt>
        </div>
        <div class="pi-info" v-if="isShowImg">
          <p class="font-price">
            <span v-if="info.price">¥{{info.price.toFixed(2)}}</span>
            <span class="del" v-if="info.delprice > 0">{{info.delprice.toFixed(2)}}</span>
          </p>
          <p>已选：{{info.color?'"'+info.color+'"':''}} {{info.size?'"'+info.size+'"':''}}</p>
        </div>
        <i class="ico-X" @click="close"></i>
      </div>
      <div class="pi-opts">
        <div class="flex">
          <label>规格</label>
          <div class="pi-cells flex-wrap">
            <span
              v-for="(i,idx) in sizes"
              :key="i.id"
              :class="{disable:!i.ok, act:i.ok&&idx===sizeSelectedIdx}"
              @click="ckCell('size',idx)"
            >{{i.sizeName}}</span>
          </div>
        </div>
        <div class="flex">
          <label>颜色</label>
          <div class="pi-cells flex-wrap">
            <span
              v-for="(i,idx) in colors"
              :key="i.id"
              :class="{disable:!i.ok, act:i.ok&&idx===colorSelectedIdx}"
              @click="ckCell('color',idx)"
            >{{i.colorName}}</span>
          </div>
        </div>
        <div class="flex pi-count-box">
          <label>数量</label>
          <div class="pi-count flex-aic">
            <i v-if="!isDistribution" class="ico-cut" @click="cgCount(-1)"></i>
            <span>{{count}}</span>
            <i v-if="!isDistribution" class="ico-add" @click="cgCount(1)"></i>
          </div>
          <span
            class="color-red"
            v-show="info.stockcount>0&&info.stockcount<6"
          >(仅剩{{info.stockcount}}件)</span>
          <span
            class="color-red"
            v-show="info.limitcount>0&&count>=info.limitcount"
          >(限购{{info.limitcount}}件)</span>
        </div>
        <span v-if="!isShowImg" style="font-size:12px;color:#999;">(如多件商品需要跟换颜色规格,请选择具体数量)</span>
      </div>
      <div class="pi-btm">
        <button type="button" :disabled="noitem" @click="submit">{{noitem ? '请选择颜色规格': '确定'}}</button>
      </div>
    </div>
  </div>
</template>
<script>
import { ProdGetItems } from "../../api/product";
import { ENUM } from "../../util";
const PT = ENUM.ProductType;
export default {
  name: "ProductItems", // usage tag: product-items
  props: {
    show: { type: Boolean, default: false },
    isShowImg: { type: Boolean, default: true }, // 售后传过来  是否显示商品图片 false不显示图片  true 显示图片
    productInfo: Object,
    isGroupBuy: { type: Boolean, default: false },
    isDistribution: { type: Boolean, default: false },
    helpType: { type: Boolean, default: false }
  },
  data() {
    return {
      ifFirstAjax: true,
      productInfoBase: {},
      count: 1,
      colorSelectedIdx: -1,
      sizeSelectedIdx: -1,
      propertyList: [],
      colors: [],
      sizes: []
    };
  },
  computed: {
    noitem() {
      return this.colorSelectedIdx < 0 || this.sizeSelectedIdx < 0;
    },
    info() {
      this.productInfoBase = { ...this.productInfo };
      if (this.productInfo && this.productInfo.id) {
        this.productInfoBase.mainpic = this.productInfoBase.mainpic.split(
          "|"
        )[0];
        this.productInfoBase = this.dealPrice(this.productInfoBase);
        if (!this.isDistribution) {
          this.getItems();
        }
      }

      let colorSelectedItem = this.colors[this.colorSelectedIdx] || {};
      let sizeSelectedItem = this.sizes[this.sizeSelectedIdx] || {};

      let okcolor = [];
      let oksize = [];
      let item = {};

      this.propertyList.map(i => {
        if (
          this.colorSelectedIdx < 0 ||
          (colorSelectedItem.id === i.colorid && i.stockcount > 0)
        )
          oksize.push(i.sizeid);
        if (
          this.sizeSelectedIdx < 0 ||
          (sizeSelectedItem.id === i.sizeid && i.stockcount > 0)
        )
          okcolor.push(i.colorid);

        if (
          colorSelectedItem.id === i.colorid &&
          sizeSelectedItem.id === i.sizeid
        )
          item = { ...i };
      });

      this.colors = this.colors.map(c => {
        c.ok = okcolor.findIndex(f => f === c.id) > -1;
        return c;
      });
      this.sizes = this.sizes.map(s => {
        s.ok = oksize.findIndex(f => f === s.id) > -1;
        return s;
      });

      if (!item.id) {
        item = {
          ...this.productInfoBase,
          stockcount: 0,
          colorid: colorSelectedItem.id,
          color: colorSelectedItem.colorName,
          sizeid: sizeSelectedItem.id,
          size: sizeSelectedItem.size
        };
      }

      if (this.isGroupBuy) {
        item.price = this.productInfoBase.price;
      }
      item.limitcount = this.productInfoBase.limitcount;

      return item;
    }
  },
  methods: {
    getItems() {
      if (
        (this.productInfo.productid && this.ifFirstAjax) ||
        (this.productInfo.productid && this.isDistribution)
      ) {
        this.ifFirstAjax = false;
        this.count = 1;
        this.colorSelectedIdx = -1;
        this.sizeSelectedIdx = -1;

        // ProdGetItems
        let optionsparam; // , IsGetProductItems
        // if(this.isShowImg){

        //   IsGetProductItems = ProdGetItems
        // }else{
        //     optionsparam ={
        //       orderItemId: this.productInfoBase.orderitemid
        //     }
        //      IsGetProductItems = GetProductItems
        // }
        optionsparam = {
          productid:
            this.productInfoBase.productid || this.productInfo.productid
        };
        if (this.isDistribution) {
          optionsparam = {
            productid: this.productInfo.productid
          };
        }

        ProdGetItems(optionsparam)
          .then(res => {
            if (res && res.length > 0) {
              let colors = [];
              let sizes = [];
              let colorIndex = 0;
              let sizeIndex = 0;

              let resultTemp = res.map(i => {
                colorIndex = i.colororder;
                sizeIndex = i.sizeorder;

                if (colors[colorIndex])
                  if (colors[colorIndex].id !== i.colorid) colorIndex++;

                colors[colorIndex] = {
                  colorName: i.color,
                  id: i.colorid,
                  ok: true
                };

                if (sizes[sizeIndex])
                  if (sizes[sizeIndex].id !== i.sizeid) sizeIndex++;

                sizes[sizeIndex] = {
                  sizeName: i.size,
                  id: i.sizeid,
                  ok: true
                };

                i = this.dealPrice(i);
                return i;
              });

              if (colors.length > 0) colors = colors.filter(i => i);
              if (sizes.length > 0) sizes = sizes.filter(i => i);

              // console.log('deal items: ', result, colors, sizes)
              this.colors = colors;
              this.sizes = sizes;
              this.propertyList = resultTemp;
            } else this.toast("商品已下架");
          })
          .catch(e => {
            console.error("商品子项加载失败", e);
          });
      }
    },

    dealPrice(i) {
      i.delprice = 0;
      if (i.specialprice > 0 && i.specialprice !== i.saleprice) {
        i.price = i.specialprice;
        i.delprice = i.saleprice;
      } else if (i.groupPrice < 999999 && this.isGroupBuy) {
        i.price = i.groupPrice;
      } else {
        i.price = i.saleprice;
      }
      //  else if(i.helpPrice < 999999 && this.helpType) {
      //   i.price = i.saleprice - i.helpPrice
      // }
      switch (i.producttype) {
        case PT.activity:
          if (i.salestatus !== 1) {
            i.price = i.saleprice;
            i.delprice = 0;
            i.specialprice = 0;
            i.producttype = PT.normal;
          }
          break;
        case PT.bees:
        case PT.sign:
          // 暂时不做 置空特价
          if (i.delprice > 0) i.price = i.delprice;
          i.delprice = 0;
          i.producttype = PT.normal;
          break;
      }
      return i;
    },
    ckCell(name, idx) {
      let current = this[name + "s"][idx];
      let tempIndex = this[name + "SelectedIdx"];
      if (current && current.ok) {
        if (tempIndex === -1) tempIndex = idx;
        else tempIndex = tempIndex === idx ? -1 : idx;
        this[name + "SelectedIdx"] = tempIndex;
      }
    },
    cgCount(payload) {
      let _ = this;
      let info = _.info;
      let count = this.count;
      if (this.helpType && sessionStorage.getItem("cuttype")) {
        this.toast("亲,只能选择一件哦~");
        // sessionStorage.removeItem('cuttype',1)
        return;
      }
      if (_.noitem) {
        this.toast("请选择颜色尺码");
        return;
      }

      count += payload;
      if (count < 1) count = 1;
      if (count > info.stockcount) {
        count = info.stockcount;
        this.toast(`库存仅剩${info.stockcount}件`);
      }
      if (info.limitcount > 0 && count > info.limitcount) {
        count = info.limitcount;
        this.toast(`该商品限购${info.limitcount}件`);
      }
      this.count = count;
    },
    submit() {
      let _ = this;
      if (_.noitem) {
        this.toast("请选择颜色尺码");
        return;
      }
      let info = _.info;
      let ret = {
        ...this.productInfoBase,
        ...info,
        id: info.id,
        productitemid: info.id,
        productname: this.productInfoBase.name,
        count: _.count,
        isok: true
      };
      // 移除商品主体信息的大体积字段
      delete ret.name;
      delete ret.brandmemo;
      delete ret.description;
      delete ret.sizedesc;
      delete ret.texture;

      // ret.specialprice = 0
      // if (ret.delprice > 0) {
      //   ret.saleprice = ret.delprice
      //   ret.specialprice = ret.price
      // } else ret.saleprice = ret.price

      _._close({ ...ret });
    },
    close() {
      this._close();
    },
    _close(payload = null) {
      let _ = this;

      // console.log('product item submit', payload)
      _.$emit("close", payload);
    }
  },

  watch: {
    productInfo(val, old) {
      let _ = this;
      if (_.productInfo && _.productInfo.id) {
        _.ifFirstAjax = true;
        _.getItems();
      }
      // if(val.id!=old.id) this.getItems()
      // console.log('---------',this.productInfo)
      // if (this.productInfo && this.productInfo.id && this.isDistribution) {
      //   this.getItems();
      // }
    }
  }
};
</script>
<style scoped>
.product-items {
  position: fixed;
  z-index: 101;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}
.product-items.show {
  pointer-events: auto;
}
.pi-bg {
  width: 100%;
  height: 100%;
  background-color: transparent;
  opacity: 0;
  transition: all 0.2s ease;
}
.show .pi-bg {
  background-color: #000;
  opacity: 0.5;
}
.pi-main {
  position: absolute;
  left: 0;
  bottom: 0;
  transform: translateY(150%);
  transition: transform 0.3s ease-out;
  width: 100%;
  height: 70%;
  background-color: #fff;
}
.show .pi-main {
  transform: translateY(0);
}

.pi-top {
  padding-top: 10px;
}
.textRight {
  text-align: right;
}
.textRight i.ico-X {
  margin-right: 10px;
}
.pi-top .pi-img {
  width: 35%;
  margin: -40px 15px 0;
}
.pi-info {
  width: 45%;
}
.pi-info .font-price {
  font-size: 20px;
}
.pi-info p:not(.font-price) {
  font-size: 12px;
  color: #666;
  margin-top: 10px;
}

.pi-opts {
  font-size: 14px;
  line-height: 24px;
  padding: 5px 10px;
  max-height: 65%;
  overflow-y: scroll;
}
.pi-opts > div {
  padding: 5px 0;
}
.pi-opts label {
  width: 10%;
  vertical-align: top;
}
.pi-cells {
  width: 90%;
  padding: 0 5px;
}
.pi-cells > span {
  margin: 0 5px 5px;
  padding: 0 8px;
  color: #999;
  border: 1px solid;
  border-radius: 4px;
}
.pi-cells > span.act {
  color: #fff;
  background-color: #333;
  border-color: #333;
}
.pi-cells > span.disable {
  color: #ccc;
  background-color: #eee;
  border-color: #eee;
}
.pi-count-box {
  line-height: 30px;
}
.pi-count {
  color: #999;
  border: 1px solid;
  border-radius: 2px;
  margin: 0 10px;
}
.pi-count > span {
  width: 60px;
  text-align: center;
}
.pi-count .ico-cut {
  border-right: 1px solid;
}
.pi-count .ico-add {
  border-left: 1px solid;
}
.pi-btm {
  position: absolute;
  bottom: 0;
  width: 100%;
}
.pi-btm button {
  width: 100%;
  background-color: #333;
  color: #fff;
  height: 50px;
  border: none;
  font-size: 1rem;
}
.pi-btm button[disabled] {
  background-color: rgba(0, 0, 0, 0.3);
}
</style>

